package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import com.itheima.service.ExprListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService deptService;

    @Autowired
    private ExprListService exprListService;

    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());

        page.addOrder(OrderItem.desc("create_time"));

        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(),param.getEnd());

        // 调用page方法完成分页查询
        page = page(page, queryWrapper);

        List<Emp> emps = page.getRecords();

        List<Long> deptIds  = emps.stream().map(emp -> emp.getDeptId()).collect(Collectors.toList());

        if (!deptIds.isEmpty()) {
            List<Dept> depts = deptService.listByIds(deptIds);

            // 将部门名称封装到员工对象中
            emps.forEach(emp -> {
                depts.forEach(dept -> {
                    if (emp.getDeptId() != null && emp.getDeptId().equals(dept.getId())) {
                        emp.setDeptName(dept.getName());
                    }
                });
            });
        }

        // 封装结果并返回
        return new PageResult<>(page.getTotal(), emps);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        save(emp);

        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> {
            expr.setEmpId(emp.getId());
        });
        exprListService.saveBatch(exprList);
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = getById(id);
        if (emp != null) {
            List<EmpExpr> list = exprListService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id));
            emp.setExprList(list);
        }
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        updateById(emp);

        exprListService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));

        List<EmpExpr> exprList = emp.getExprList();
        if(exprList != null){
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        }
        exprListService.saveBatch(exprList);
    }

    @Override
    public void removeEmpByIds(List<Integer> ids) {
        removeBatchByIds(ids);

        exprListService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));
    }
}
